import React from "react";
import { Button, Space } from "antd";

interface Option {
  label: string;
  value: number | string;
}
interface Props {
  options: Option[];
  value?: Array<string | number>;
  onChange?: (value: Array<string | number>) => void;
  hasAll?: boolean;
  totalNum?: number | string;
}

const ButtonGutterGroup: React.FC<Props> = ({options = [], value = [], onChange, hasAll = true, totalNum = 0}) => {

  const isChecked = (val: number | string) => {
    return value?.includes(val)
  }

  const onSelected = (val: number | string) => {
    const index = value?.findIndex(v => v === val);
    const arr: Array<string | number> = [...value];
    if (index >= 0) {
      arr.splice(index, 1);
    } else {
      arr.push(val);
    }
    onChange(arr.filter(v => v !=='all' ));
  }
  const handleAllClick = () => {
    if (value.includes('all')) {
      onChange(value.filter(v => v !== 'all'));
    } else {
      onChange(['all']);
    }
  }

  return (
    <Space style={{flexWrap:'wrap'}}>
      {
        hasAll && (
          <Button
            onClick={handleAllClick} 
            type={isChecked('all') ? 'primary' : 'default'}
            key='all' 
          >
            {totalNum > 0 ? `全部(${totalNum})` : '全部'}
          </Button>
        )
      }
      {
        options?.map((v: { value: number | string; label?: number | string; }) => 
          <Button
            onClick={() => onSelected(v.value)} 
            type={isChecked(v.value) ? 'primary' : 'default'}
            key={v.value} 
          >
            {v?.label}
          </Button>
        )
      }
    </Space>
  );
}
export default ButtonGutterGroup;